<template>
	<div class="login">
		<!-- 头部 -->
		<MyHead></MyHead>
		<!-- 如果父组件上的属性直接作用到子组件的根标签上，可以不做绑定 -->

		<!-- 用户名 -->
		<MyInput v-model="user.username" type="text" placeholder="用户名 / 手机号码"
			:rules="/^1\d{10}$|^[A-z]\w{2,10}$|^10{2}\d{2,3}$/" msg="用户名或手机号码不正确!">
		</MyInput>

		<!-- 密码 -->
		<MyInput v-model="user.password" type="password" placeholder="密码" :rules="/./" msg="密码格式错误!">
		</MyInput>

		<div class="login_tips">
			没有账号?<router-link replace to="/register">去注册</router-link>
		</div>

		<MyButton @click="loginFn" type="danger">登录</MyButton>
	</div>
</template>

<script>
	import MyHead from '../components/MyHead.vue'
	import MyButton from '../components/MyButton.vue'
	import MyInput from '../components/MyInput.vue'
	import { userLoginApi } from '../apis/user.js'
	import { setToken , setID } from '../utils/localData.js'
	export default {
		data() {
			return {
				user: {
					username: '15626230051',
					password: 'nimadebi~'

				}
			}
		},

		components: {
			MyButton,
			MyInput,
			MyHead
		},

		methods: {
			loginFn() {
				const nameReg = /^1\d{10}$|^[A-z]\w{2,10}$|^10{2}\d{2,3}$/;
				if(nameReg.test(this.user.username)){
					userLoginApi({
						username: this.user.username,
						password: this.user.password
					})
					.then(res => {
						const { message } = res.data;
						const { token } = res.data.data;
						const { id } = res.data.data.user;
						console.log(res);
						if(message === "登录成功" && res.status === 200){
							setID(id);
							setToken(token);
							const {formUrl} = this.$route.params;
							if(formUrl){
								location.href = formUrl;
							}else{
								this.$router.replace({path: '/user' , query: {id: id}})
							}
							//跳转到个人页，并传递token
							this.$toast.success('登陆成功');
						}
					})
				}else{
					this.$toast("用户名或密码错误！");
				}

			},



//一个组件上的 v-model 默认会利用名为 value 的 prop 和名为 input 的事件
/* 			getInput1(e) {
				console.log(e)
								this.user.username = e;
								this.user.password = e;

			} */
		

		}

	}
</script>

<style lang="less" scoped>
	.login_tips{
		text-align: right;
		padding-right: 30px;
	}
</style>
